package com.sh.personnel.util;


import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * @author Administrator
 * @date 2019/12/25 19:07
 */
public class Base64Util {

    /**
     * 将字节数组转为base64格式
     * @param data
     * @return
     */
    public static String byteArrayToBase64(byte[] data) {
        String base64 = Base64.getEncoder().encodeToString(data);
        return base64;
    }

    /**
     * 将base64转为字节数组
     * @param base64
     * @return
     */
    public static byte[] base64TobyteArray(String base64) {
        byte[] data = Base64.getDecoder().decode(base64);
        return data;
    }

    public static String base64ToFileOnClass(String dir, String base64) {
        return base64FileOnClass(dir, RandomUtil.generateUuid(), base64);
    }

    public static String base64ToFile(String dir, String filename, String base64) {
        return base64File(dir, filename, base64);
    }

    /**
     * 将base64转为图片文件
     * @param dir
     * @param filename
     * @param base64
     */
    private static String base64FileOnClass(String dir, String filename, String base64) {
        base64 = base64.substring(base64.indexOf(",") + 1, base64.length());
        byte[] data = Base64.getDecoder().decode(base64);
        try {
            File file = new File(ResourceUtils.getFile("classpath:") + dir);
            if(!file.exists()) file.mkdirs();
            filename = File.separator + filename + ".jpg";
            FileOutputStream fos = new FileOutputStream(file + filename);
            fos.write(data);
            fos.close();
            return dir + filename;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将base64转为图片文件
     * @param dir
     * @param filename
     * @param base64
     */
    private static String base64File(String dir, String filename, String base64) {
        base64 = base64.substring(base64.indexOf(",") + 1, base64.length());
        byte[] data = Base64.getDecoder().decode(base64);
        File file = new File(dir);
        if(!file.exists()) file.mkdirs();
        dir = dir + filename + ".jpg";
        try {
            FileOutputStream fos = new FileOutputStream(dir);
            fos.write(data);
            fos.close();
            return dir;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
